import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from "../store/index"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import(/* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect: '/user/cart',
    component: () => import(/* webpackChunkName: "user" */ '../views/User.vue'),
    // 配置购物车子路由
    children: [{
      path: 'cart',
      name: 'cart',
      component: () => import(/* webpackChunkName: "cart" */ '../components/user/Cart.vue'),
    }]
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem('x-auth-token')
    //   if (token) {
    //     next()
    //   } else {
    //     store.dispatch('showToast/asyncChangeIsShowToast', {
    //       isShow: true,
    //       msg: '请先登录!',
    //       type: 'danger'
    //     })
    //   }
    // }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import(/* webpackChunkName: "details" */ '../views/Details.vue')
  },
  {
    path: '*',
    name: 'error',
    component: () => import(/* webpackChunkName: "error" */ '../components/Error.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局导航守卫
// router.beforeEach((to, from, next) => {
//   if (to.path == '/user') {
//     let token = localStorage.getItem('x-auth-token')
//     if (token) {
//       next()
//     } else {
//       store.dispatch('showToast/asyncChangeIsShowToast', {
//         isShow: true,
//         msg: '请先登录!',
//         type: 'danger'
//       })
//     }
//   }
//   next()
// })

// 解决重复点击同一路径报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};
export default router
